#!/usr/bin/env ruby

# change to current directory when invoked on its own
Dir.chdir(File.dirname(File.expand_path(__FILE__))) if __FILE__ == $0

# add current directory to load path
$FLUXR_HOME = File.dirname(File.expand_path(__FILE__))
$: << $FLUXR_HOME

$:<< "/home/URBACON/mzukowski/workspace/OpenWFEru/openwfe-ruby/lib"

require 'rubygems'
gem 'camping', '~> 1.5'
require 'camping'

gem 'reststop'
require 'reststop'

#gem 'openwferu', '~> 0.9.12'

require 'active_support'
require 'yaml'
require 'fileutils'

Camping.goes :Fluxr

module Fluxr
  def init_logger
    $LOG = Fluxr::Utils::Logger.new(Fluxr::Conf.log[:file])
    $LOG.level = "Fluxr::Utils::Logger::#{Fluxr::Conf.log[:level]}".constantize
  end
  module_function :init_logger

#  def init_db_logger
#    begin
#      if Fluxr::Conf.db_log
#        log_file = Fluxr::Conf.db_log[:file] || 'fluxr_db.log'
#        Fluxr::Models::Base.logger = Logger.new(log_file)
#        Fluxr::Models::Base.logger.level = "Fluxr::Utils::Logger::#{Fluxr::Conf.db_log[:level] || 'DEBUG'}".constantize
#      end
#    rescue Errno::EACCES => e
#      $LOG.warn "Can't write to database log file at '#{log_file}': #{e}"
#    end
#  end
#  module_function :init_db_logger

  def load_participants
    reg = Fluxr::Conf[:participant_registration]
    
    unless File.exists? reg
      raise "Cannot load participants because the participant registration file"+
        " '#{reg}' does not exist! See Fluxr the documentation for more"+
        " information."
    end
    
    $LOG.debug("About to load participants from '#{reg}'...")
    require reg
    $LOG.info("Participants loaded from '#{reg}'.")
  end
  module_function :load_participants
  
  def unload_participants
    $LOG.debug("About to unload participants...")
    $LOG.info("Participants unloaded.")
  end
  module_function :unload_participants

  def reload_participants
    unload_participants
    load_participants
  end

end

require 'fluxr/utils'
require 'fluxr/models'
require 'fluxr/conf'
require 'fluxr/helpers'
require 'fluxr/views'
require 'fluxr/controllers'

Fluxr.init_logger

# do initialization stuff
def Fluxr.create
  Fluxr::Models.create_schema
  
  $LOG.info("Fluxr server initialized.")
  
  $LOG.debug("Configuration is:\n#{$CONF.to_yaml}")

#  unless File.exist? Fluxr::Conf.workflows_dir
#    $LOG.info("Creating workflows directory in #{Fluxr::Conf.workflows_dir}")
#    FileUtils.mkpath Fluxr::Conf.workflows_dir
#  end
  
  require 'openwfe/engine/file_persisted_engine'
  require 'openwfe/workitem'
  require 'openwfe/engine/engine'
  require 'openwfe/participants/enoparticipants'
  require 'openwfe/worklist/storeparticipant'
  
  engine_options = {}
  engine_options[:remote_definitions_allowed] = true
  
  engine_options[:work_directory] = Fluxr::Conf.work_dir
  engine_options[:logger] = $LOG
  
  unless File.exist? Fluxr::Conf.base_dir
    $LOG.info("Creating base directory in #{Fluxr::Conf.base_dir}")
    FileUtils.mkpath Fluxr::Conf.base_dir
  end
  
  @@engine = OpenWFE::CachedFilePersistedEngine.new(engine_options)
  
  load_participants
  
  #@@engine.reschedule
end


# this gets run if we launch directly (i.e. `ruby fluxr.rb` rather than `camping fluxr`)
if __FILE__ == $0 || $RUN
  #Fluxr::Models::Base.establish_connection(Fluxr::Conf.database)
  #Fluxr.init_db_logger unless Fluxr::Conf.server.to_s == 'mongrel'
  
  require 'fluxr/postambles'
  include Fluxr::Postambles

  if $PID_FILE && (Fluxr::Conf.server.to_s != 'mongrel' || Fluxr::Conf.server.to_s != 'webrick')
    $LOG.warn("Unable to create a pid file. You must use mongrel or webrick for this feature.")
  end

#  begin
    raise NoMethodError if Fluxr::Conf.server.nil?
    send(Fluxr::Conf.server)
#  rescue NoMethodError => e
#    # FIXME: this rescue can sometime report the incorrect error messages due to other underlying problems
#    #         raising a NoMethodError
#    if Fluxr::Conf.server
#      raise e, "The server setting '#{Fluxr::Conf.server}' in your config.yml file is invalid."
#    else
#      raise e, "You must have a 'server' setting in your config.yml file. Please see the Fluxr documentation."
#    end
#  end
end 